package com.dk.testflow;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dk.action.ActionContext;
import com.dk.domain.ActionEntity;
import com.dk.domain.ApiAutoTestEntity;
import com.dk.domain.action.CaseActionBodyEntity;
import com.dk.enumerate.DkRuleEnum;
import com.dk.exception.ExcelDataException;
import com.dk.factory.ActionFactory;
import com.dk.factory.FactoryProducer;
import com.dk.testcase.BaseCase;
import com.dk.util.log.Log;
import com.google.common.base.Strings;

/**
 * 后置动作执行环节
 */
public class AfterActionLink extends ApiAutoTestChain{
    /**
     * 后置动作执行链
     * @param apiAutoTestEntity 接口自动测试对象
     */
    @Override
    public void executeTestChain(ApiAutoTestEntity apiAutoTestEntity) throws ExcelDataException {
        if (!Strings.isNullOrEmpty(apiAutoTestEntity.getAfterAction())) {
            Log.info("---【后置动作】:用例编号:" + apiAutoTestEntity.getCaseNum() + ";用例名称:" + apiAutoTestEntity.getCaseName() + "开始执行后置动作");
            //获取测试用例需要执行的后置动作编码数组
            JSONArray Actions = JSON.parseObject(apiAutoTestEntity.getAfterAction()).getJSONArray(DkRuleEnum.ACTION_NUM.getValue());
            //遍历数组执行后置动作
            for (int i = 0; i < Actions.size(); i++) {
                //根据动作编码获取动作对象
                ActionEntity actionEntity = BaseCase.actionEntityMap.get(Actions.get(i));
                if(actionEntity.getActionType().equals(DkRuleEnum.ACTIONTYPE_CASE.getValue())){
                    //将动作主体内容转换为用例执行主体对象
                    CaseActionBodyEntity caseActionBodyEntity = JSON.parseObject(actionEntity.getActionBody(), CaseActionBodyEntity.class);
                    if(caseActionBodyEntity.getCaseNum().equals(apiAutoTestEntity.getCaseNum())){
                        throw new ExcelDataException("---【error】:！！！不允许测试用例调用自己做前置动作/后置动作,CaseNum:"+apiAutoTestEntity.getCaseNum()+";");
                    }
                }
                Log.info("---【后置动作】:开始执行,ActionNum:" + actionEntity.getActionNum() + ";");
                //获取动作策略工厂
                ActionFactory actionFactory = (ActionFactory) FactoryProducer.getFactory(DkRuleEnum.ACTION.getValue());
                //根据动作类型获取动作策略对象执行动作策略
                new ActionContext(actionFactory.getAction(actionEntity.getActionType())).excuteAction(actionEntity);
            }
        }
    }
}
